package com.mfks.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;

import com.alibaba.dubbo.config.annotation.Service;
import com.mfks.mapper.TTestTitleMapper;
import com.mfks.model.TMemberTest;
import com.mfks.model.TTestOption;
import com.mfks.model.TTestResult;
import com.mfks.model.TTestTitle;
import com.mfks.service.MemberTestService;
import com.mfks.service.TestOptionService;
import com.mfks.service.TestResultService;
import com.mfks.service.TestTitleService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.InstanceUtil;

/**
 * <p>
 * 测试题目 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-12-28
 */
@Service
@CacheConfig(cacheNames = "TTestTitle")
public class TestTitleServiceImpl extends BaseServiceImpl<TTestTitle, TTestTitleMapper> implements TestTitleService {
    @Autowired
    private TestOptionService optionService;
    @Autowired
    private TestResultService resultService;
    @Autowired
    private MemberTestService memberTestService;

    @Override
    public Pagination<TTestTitle> query(Map<String, Object> params) {
        params.put("asc", "test_type, title_seq");
        params.put("desc", "id_");
        return super.query(params);
    }

    @Override
    public Pagination<TTestTitle> randomTestTitles(Map<String, Object> params) {
        params.put("asc", "test_type, title_seq");
        params.put("desc", "id_");
        Pagination<TTestTitle> list = super.query(params);
        IntStream.range(0, list.getRecords().size()).parallel().forEach(i -> {
            TTestTitle testTitle = list.getRecords().get(i);
            testTitle.setTitleAnswer(null);
            List<TTestOption> options = optionService.queryList(new TTestOption().setTestId(testTitle.getId()));
            for (TTestOption testOption : options) {
                testOption.setOptionVal(null);
            }
            testTitle.setOptions(options);
        });
        return list;
    }

    @Override
    public Set<TMemberTest> submit(Long memberId, String[] answers) {
        Set<TMemberTest> result = InstanceUtil.newHashSet();
        Map<String, BigDecimal> groupResult = InstanceUtil.newHashMap();
        List<TTestResult> results = null;
        TTestTitle title = null;
        StringBuilder sb = new StringBuilder();
        for (String answer : answers) {
            BigDecimal val = new BigDecimal("0");
            String[] row = answer.split("\\`");
            title = super.queryById(Long.parseLong(row[0]));
            if ("4".equals(title.getTitleType()) && row[1].contains(",")) {
                results = resultService.queryList(new TTestResult().setTestType(title.getTestType()));
                for (TTestResult testResult : results) {
                    logger.info(row[1]);
                    String[] GN = testResult.getResultTitle().split(",");
                    testResult.setResultTitle(sb.toString());
                    String[] e = row[1].split(",");
                    for (String element : e) {
                        String r = testResult.getResultInfo().replaceFirst("选择内容", GN[Integer.parseInt(element)]);
                        testResult.setResultInfo(r);
                    }
                    saveMemberTestResult(memberId, testResult, val);
                }
            } else if ("6".equals(title.getTestType())) {
                List<TTestOption> list = optionService.queryList(new TTestOption().setTestId(title.getId()));
                for (TTestOption testOption : list) {
                    if (row[1].equals(testOption.getOptionKey())) {
                        sb.append(testOption.getTestOption());
                        break;
                    }
                }
            } else {
                logger.info(row[0] + "=" + row[1]);
                if ("1".equals(title.getTitleType())) {
                    if (row[1].equals(title.getTitleAnswer()) && title.getTitleVal() != null) {
                        val = val.add(title.getTitleVal());
                    } else {
                        List<TTestOption> list = optionService.queryList(new TTestOption().setTestId(title.getId()));
                        for (TTestOption testOption : list) {
                            if (row[1].equals(testOption.getOptionKey())) {
                                val = val.add(testOption.getOptionVal());
                                break;
                            }
                        }
                    }
                } else if ("2".equals(title.getTitleType())) {
                    List<TTestOption> list = optionService.queryList(new TTestOption().setTestId(title.getId()));
                    for (TTestOption testOption : list) {
                        if (row[1].contains(testOption.getOptionKey())) {
                            val = val.add(testOption.getOptionVal());
                        }
                    }
                    if (title.getTitleAnswer().equals(row[1])) {
                        val = val.add(title.getTitleVal());
                    }
                } else if ("3".equals(title.getTitleType())) {
                    if (title.getTitleAnswer().equals(row[1])) {
                        val = val.add(title.getTitleVal());
                    }
                }
                String group = title.getTitleGroup();
                val = val.add(DataUtil.ifNull(groupResult.get(group), new BigDecimal("0")));
                groupResult.put(group, val);
                if (results == null) {
                    results = resultService.queryList(new TTestResult().setTestType(title.getTestType()));
                }
                for (TTestResult testResult : results) {
                    if (DataUtil.isEmpty(testResult.getTestGroup()) || group.equals(testResult.getTestGroup())) {
                        if (val.doubleValue() >= testResult.getValMin().doubleValue()
                                && val.doubleValue() <= testResult.getValMax().doubleValue()) {
                            logger.info("VAL=" + val);
                            saveMemberTestResult(memberId, testResult, val);
                        }
                    }
                }
            }
        }
        logger.info(groupResult);
        if (title != null) {
            TMemberTest entity = new TMemberTest().setMemberId(memberId).setTestType(title.getTestType());
            result.addAll(memberTestService.queryList(entity));
        }
        return result;
    }

    private void saveMemberTestResult(Long memberId, TTestResult testResult, BigDecimal val) {
        TMemberTest entity = new TMemberTest().setMemberId(memberId).setTestType(testResult.getTestType())
                .setTestGroup(testResult.getTestGroup());
        TMemberTest memberTest = memberTestService.selectOne(entity);
        if (memberTest != null) {
            entity.setId(memberTest.getId());
        }
        entity.setTestVal(val).setTestResult(testResult.getResultTitle()).setResultInfo(testResult.getResultInfo());
        memberTestService.update(entity);
    }
}
